package cn.zhoushengdao.bingwallpaper

import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "data")

class AppData(private val context: Context) {
    companion object {
        private val AUTO_CHANGE_ENABLED = booleanPreferencesKey("auto_change_enabled")
        private val CURRENT_WALLPAPER_URL = stringPreferencesKey("current_wallpaper_url")
        private val CURRENT_LOCALE = stringPreferencesKey("current_locale")
        private val WALLPAPERS_JSON = stringPreferencesKey("wallpapers_json")

        const val DEFAULT_AUTO_CHANGE = false
        const val DEFAULT_LOCALE = "zh-CN"
    }

    val autoChangeEnabled: Flow<Boolean>
        get() = context.dataStore.data.map { data ->
            data[AUTO_CHANGE_ENABLED] ?: DEFAULT_AUTO_CHANGE
        }
    val currentWallpaperUrl: Flow<String>
        get() = context.dataStore.data.map { data ->
            data[CURRENT_WALLPAPER_URL] ?: ""
        }
    val currentLocale: Flow<String>
        get() = context.dataStore.data.map { data ->
            data[CURRENT_LOCALE] ?: DEFAULT_LOCALE
        }
    val wallpapers: Flow<List<WallpaperData>>
        get() = context.dataStore.data.map { data ->
            data[WALLPAPERS_JSON]?.let { json ->
                Gson().fromJson(json, object : TypeToken<List<WallpaperData>>() {}.type)
            } ?: emptyList()
        }

    suspend fun setAutoChangeEnabled(enabled: Boolean) {
        context.dataStore.edit { it[AUTO_CHANGE_ENABLED] = enabled }
    }

    suspend fun setCurrentWallpaperUrl(url: String) {
        context.dataStore.edit { it[CURRENT_WALLPAPER_URL] = url }
    }

    suspend fun setCurrentLocale(locale: String) {
        context.dataStore.edit { it[CURRENT_LOCALE] = locale }
    }

    suspend fun setWallpapers(wallpapers: List<WallpaperData>) {
        context.dataStore.edit { it[WALLPAPERS_JSON] = Gson().toJson(wallpapers) }
    }

    suspend fun debugPrint() {
        val preferences = context.dataStore.data.first()
        Log.d(
            "BingWallpaper",
            "AppPreferences(\n\tAutoChangeEnabled=${preferences[AUTO_CHANGE_ENABLED]},\n\tCurrentWallpaperUrl=\"${preferences[CURRENT_WALLPAPER_URL]}\",\n\tCurrentLocale=\"${preferences[CURRENT_LOCALE]}\"\n)"
        )
    }
}